import json
import subprocess
from pathlib import Path
from typing import List

from build_feature.extract_npm_different_version_functions.core.function_info import FunctionInfo
from build_feature.extract_npm_different_version_functions.core.function_info_extractor import FunctionInfoExtractor
from build_feature.extract_npm_different_version_functions.js_handle_module.js_function_info import JSAndTSFunctionInfo


class JSAndTSFunctionInfoExtractor(FunctionInfoExtractor):

    def extract(self, repository_path,js_output_path,library) -> List[FunctionInfo]:
        """
        执行JS函数提取器并获取结果
        """
        # 调用Node.js执行脚本
        js_path = Path(__file__).parent / "js_ts_extract.js"
        process = subprocess.run(
            ["node", str(js_path), repository_path, js_output_path,library],
            capture_output=True,
            text=True,
            encoding="utf-8"
        )

        # 错误处理
        if process.returncode != 0:
            raise RuntimeError(f"JS执行失败:\n{process.stderr}")

        # 解析输出路径
        try:
            output = json.loads(process.stdout.splitlines()[-1])  # 获取最后一行JSON输出
        except json.JSONDecodeError:
            raise ValueError("无法解析JS输出")

        # 读取生成的文件
        with open(output["mainOutput"], "r", encoding="utf-8") as f:
            main_data = json.load(f)

        # 对函数信息进行包装
        main_function_info = []
        for function in main_data["functions"]:
            main_function_info.append(JSAndTSFunctionInfo(function))
        return main_function_info
